import React, { useEffect, useState } from 'react';
import { useLayout } from "../../../hooks/useLayout.tsx";
import { useLocation } from "react-router-dom";
import {Button, Collapse, Form, Input, message, Select, Spin} from "antd";
import {usePost, usePostManual} from "../../../hooks/useApis.ts";
import './less/pluginToolEdit.less'
import { EditOutlined } from "@ant-design/icons";
import TextArea from "antd/es/input/TextArea";
import {ParameterConfig} from "./ParameterConfig.tsx";

const PluginToolEdit: React.FC = () => {
    const { setOptions } = useLayout();
    const location = useLocation();
    const { id, pluginTitle, pluginToolTitle } = location.state || {};
    const { result: pluginToolInfo, doPost: doPostSearch, loading } = usePost('/api/v1/aiPluginTool/tool/search');
    const {  doPost: doPostUpdate } = usePostManual('/api/v1/aiPluginTool/tool/update')
    const [showLoading, setShowLoading] = useState(true);
    const [editStates, setEditStates] = useState({
        '1': false,
        '2': false,
        '3': false
    });
    const [formBasicInfo] = Form.useForm();

    useEffect(() => {
        setOptions({
            showBreadcrumb: true,
            breadcrumbs: [
                { title: '首页' },
                { title: '插件', href: `/ai/plugin` },
                { title: pluginTitle, href: `/ai/plugin` },
                { title: pluginToolTitle, href: `/ai/pluginTool` },
                { title: '修改' },
            ],
        });

        doPostSearch({
            data: {
                aiPluginToolId: id
            }
        }).then(() => {
            setTimeout(() => {
                setShowLoading(false);
            }, 1000);
        });

        return () => {
            setOptions({
                showBreadcrumb: true,
                breadcrumbs: []
            });
        };
    }, []);

    const toggleEdit = (index: string) => (event: React.MouseEvent) => {
        event.stopPropagation();
        setEditStates(prev => ({
            ...prev,
            [index]: !prev[index as keyof typeof prev]
        }));

        if (index === '1' && !editStates['1']) {
            formBasicInfo.setFieldsValue({
                id: pluginToolInfo?.data?.data?.id,
                name: pluginToolInfo?.data?.data?.name,
                description: pluginToolInfo?.data?.data?.description,
                basePath: pluginToolInfo?.data?.data?.basePath ? pluginToolInfo?.data?.data?.basePath : `/${pluginToolInfo?.data?.data?.name}`,
                baseUrl: pluginToolInfo?.data?.aiPlugin?.baseUrl,
                requestMethod: pluginToolInfo?.data?.data?.requestMethod,
            });
        }
    };

    const editPluginTool = (index: string) => (
        <div
            style={{ display: 'flex', alignItems: 'center', gap: '8px' }}
            onClick={toggleEdit(index)}
        >
            <span>{editStates[index as keyof typeof editStates] ?
                <div style={{ display: 'flex', gap: '8px' }}>
                    <Button type="primary" size="small">取消</Button>
                    <Button type="primary" size="small" onClick={() => {
                        formBasicInfo.validateFields().then((values) => {
                            // 修改基本信息
                            if (index === '1'){
                                doPostUpdate({data: {
                                        id: values.id,
                                        name: values.name,
                                        description: values.description,
                                        basePath: values.basePath,
                                        requestMethod: values.requestMethod
                                    }}).then((r) => {
                                        if (r?.data?.errorCode === 0){
                                            message.success('修改成功');
                                            doPostSearch({
                                                data: {
                                                    aiPluginToolId: id
                                                }
                                            })
                                        }

                                });
                            }

                            console.log('values');
                            console.log(values);
                        });
                    }}>保存</Button>
                </div>
                :
                <div style={{ display: 'flex', gap: '8px' }}>
                    <EditOutlined />
                    <span>编辑</span>

                </div>
            }</span>

        </div>
    );

    const collapseItems = [
        {
            key: '1',
            label: '基本信息',
            children: editStates['1'] ? (
                <Form
                    form={formBasicInfo}
                    variant="filled"
                    layout="vertical"
                >
                    <Form.Item label="id" name="id" hidden rules={[{ required: true }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label="工具名称" name="name" rules={[{ required: true }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label="工具描述" name="description" rules={[{ required: true }]}>
                        <TextArea style={{ height: 80, resize: 'none' }} />
                    </Form.Item>
                    <Form.Item label="工具路径" name="basePath" rules={[{ required: true }]}>
                        <Input addonBefore={formBasicInfo.getFieldValue('baseUrl')} />
                    </Form.Item>
                    <Form.Item label="请求方法" name="requestMethod" rules={[{ required: true }]}>
                        <Select
                            // onChange={(value) => {
                            //     setAuthType(value)
                            // }}
                            options={[
                                { value: 'Post', label: 'Post' }
                                , { value: 'Get', label: 'Get' }
                                , { value: 'Delete', label: 'Delete' }
                                , { value: 'Put', label: 'Put' }
                                , { value: 'Patch', label: 'Patch' }]}/>
                    </Form.Item>
                </Form>
            ) : (
                <div className="compact-view">
                    <div><strong>工具名称:</strong> {pluginToolInfo?.data?.data?.name || '--'}</div>
                    <div><strong>工具描述:</strong> {pluginToolInfo?.data?.data?.description || '--'}</div>
                    <div>
                        <strong>工具路径:</strong>
                        {pluginToolInfo?.data?.aiPlugin?.baseUrl
                            && pluginToolInfo?.data?.data?.basePath ?
                            pluginToolInfo?.data?.aiPlugin?.baseUrl+pluginToolInfo?.data?.data?.basePath
                            :
                            pluginToolInfo?.data?.aiPlugin?.baseUrl+'/'+pluginToolInfo?.data?.data?.name
                        }
                    </div>
                    <div><strong>请求方法:</strong> {pluginToolInfo?.data?.data?.requestMethod || '--'}</div>
                </div>
            ),
            extra: editPluginTool('1')
        },
        {
            key: '2',
            label: '配置输入参数',
            children:  (
                <ParameterConfig/>
            ),
            extra: editPluginTool('2')
        },
        {
            key: '3',
            label: '配置输出参数',
            children: <div className="compact-view">输出参数配置区域</div>,
            extra: editPluginTool('3')
        },
    ];

    if (showLoading) {
        return (
            <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
                <Spin size="large"/>
            </div>
        );
    }

    return (
        <div style={{ backgroundColor: '#F5F5F5',height: '100vh', overflow: 'auto' }}>
            <Collapse
                bordered={false}
                defaultActiveKey={['1', '2', '3']}
                items={collapseItems.map(item => ({
                    ...item,
                    style: {
                        header: { backgroundColor: '#F7F7FA' },
                        body: { backgroundColor: '#F5F5F5' },
                    },
                }))}
            />
        </div>
    );
};

export default {
    path: "/ai/pluginToolEdit",
    element: PluginToolEdit
};